package com.itheima.project.handler.aliyun.config;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.teaopenapi.models.Config;
import com.itheima.project.constant.sms.SmsConstant;
import com.itheima.project.face.SmsChannelFace;
import com.itheima.project.utils.ExceptionsUtil;
import com.itheima.project.vo.sms.SmsChannelVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;

import javax.annotation.PostConstruct;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @ClassName AlipayConfig.java
 * @Description 支付宝配置类
 */
@Slf4j
@Configuration
public class AliyunSmsConfig {

    @Autowired
    SmsChannelFace smsChannelFace;

    @Async
    @PostConstruct
    public void initConfig(){
        Timer timer = new Timer();
        timer.schedule(new InitTask(timer),10*1000);
    }

    class InitTask extends TimerTask {

        private Timer timer;

        private InitTask(Timer timer) {
            this.timer= timer;
        }

        @Override
        public void run() {
            //初始化阿里云SMS的配置信息
            smsChannelFace.findSmsChannelByChannelLabel(SmsConstant.ALIYUN_SMS);
        }
    }


    /***
     * @description 获得配置
     * @return
     */
    public Client queryClient(){
        SmsChannelVo smsChannelVo = smsChannelFace.findSmsChannelByChannelLabel(SmsConstant.ALIYUN_SMS);
        Config config = new Config()
                // 阿里云AccessKey ID
                .setAccessKeyId(smsChannelVo.getAccessKeyId())
                // 阿里云AccessKey Secret
                .setAccessKeySecret(smsChannelVo.getAccessKeySecret());
        // 访问的域名
        config.endpoint = smsChannelVo.getDomain();
        try {
            return new Client(config);
        } catch (Exception e) {
            log.error("阿里云SMS的配置信息出错：{}", ExceptionsUtil.getStackTraceAsString(e));
            return null;
        }
    }
}
